package com.atguigu.myjuc.demo;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 100个线程，每个线程加100次，求最后的number值
 */
public class CASDemo {
    private static final int COUNT_NUMBER = 100;

    private int number;

    public int getNumber() {
        return number;
    }

    public synchronized void setNumber() {
        ++number;
    }

    AtomicInteger atomicInteger = new AtomicInteger();

    public AtomicInteger getAtomicInteger() {
        return atomicInteger;
    }

    public void setAtomicInteger() {
        atomicInteger.incrementAndGet();
    }
    /*//1 需求:多线程环境【不使用】原子类AtomicInteger保证线程安全（基本数据类型）
    private int number;

    public int getNumber() {
        return number;
    }

    public synchronized void setNumber() {
        ++number;
    }

    //2 多线程环境    【使用】   原子类AtomicInteger保证线程安全（基本数据类型）
    AtomicInteger atomicInteger = new AtomicInteger();

    public AtomicInteger getAtomicInteger() {
        return atomicInteger;
    }

    public void setAtomicInteger() {
        atomicInteger.incrementAndGet();
    }*/

    public static void main(String[] args) throws InterruptedException {
        /*CASDemo casDemo = new CASDemo();
        CountDownLatch downLatch = new CountDownLatch(COUNT_NUMBER);
        for (int i = 1; i <= COUNT_NUMBER; i++) {
            new Thread(()->{
                for (int j = 0; j < COUNT_NUMBER; j++) {
                    casDemo.setNumber();
                    casDemo.setAtomicInteger();
                }
                downLatch.countDown();
            },String.valueOf(i)).start();
        }
        downLatch.await();*/
        CASDemo casDemo = new CASDemo();
        CountDownLatch downLatch = new CountDownLatch(COUNT_NUMBER);
        for (int i = 1; i <= COUNT_NUMBER; i++) {
            new Thread(()->{
                for (int j = 1; j <= COUNT_NUMBER; j++) {
                    casDemo.setNumber();
                    casDemo.setAtomicInteger();
                }
                downLatch.countDown();
            },String.valueOf(i)).start();
        }
        downLatch.await();

        System.out.println(Thread.currentThread().getName()+"\t"+ casDemo.getNumber());
        System.out.println(Thread.currentThread().getName()+"\t"+ casDemo.getAtomicInteger());
    }
}
